package com.niodata.dp.web.forms;

import com.niodata.dp.log.LogUtil;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

public class ParamsSchemaUtil {

  private static final Map<String, String> paramSchemas = new HashMap<>();
  private static final Logger logger = Logger.getLogger(
        ParamsSchemaUtil.class);

  //scan json coniguration.
  static {
    PathMatchingResourcePatternResolver resourcePatternResolver =
          new PathMatchingResourcePatternResolver();
    try {
      Resource[] resources = resourcePatternResolver
            .getResources("classpath:fs.configs/*");
      for (Resource res : resources) {
        String fileName = res.getFilename();
        String[] ss = fileName.split("/");
        String name = ss[ss.length - 1];
        name = name.split("\\.")[0];
        String json = new String(IOUtils.toByteArray(res.getInputStream()));
        logger.info("get form :" + res.getURI());
        paramSchemas.put(name, json);
      }
    } catch (IOException ioe) {
      LogUtil.logStackTrace(logger, ioe);
      throw new RuntimeException(ioe);
    }
  }

  public static String getSchemaJson(String type) {
    return paramSchemas.get(type);
  }

  public static Set<String> getConfigedSchemaNames() {
    return paramSchemas.keySet();
  }


}
